﻿using System;
using System.Collections.Generic;
using System.Drawing;
using SVM;
using Emgu.CV;
using Emgu.CV.Structure;

namespace FFTConv
{
    class GaborEmguSVMTest
    {
        Model model = null;
        RangeTransform range = null ;
        Problem problem = null;
       
        #region Train
        List<char> Symbols = new List<char>();
        public void Train()   //SVM分类
        {
            //Bitmap bitmap;
            //int sigma = 60;
            //List<Node[]> _X = new List<Node[]>();
            //List<double> _Y = new List<double>();
            //List<EmguSample> samples = new List<EmguSample>();
            //Matrix<float> trainData = new Matrix<float>(trainSampleCount, 2);

            //Matrix<float> trainClasses = new Matrix<float>(trainSampleCount, 1);

            //System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
            //dlg.Multiselect = true;
            //if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            //    return;
            //for (int i = 0; i < dlg.FileNames.Length; i++)
            //{

            //    GaborEmgu test = new GaborEmgu();
            //    bitmap = new Bitmap(dlg.FileNames[i]);
            //    //Bitmap bitmap = dlg.FileNames[i];
            //    //string str = dlg.FileNames[i];
            //    //byte[] byteImg = System.Text.Encoding.Default.GetBytes(str);
            //    EmguSample sample = new EmguSample(bitmap);
            //    sample.Gabor = test.GaborTransform(sample.Image);
            //    _X.Add(sample.ToNodes());
            //    _Y.Add(i + 1);
            //    //_X.Add(sample.ToNodes());
            //    //_Y.Add(i + 1);
            //    samples.Add(sample);
            //}

            //string dir = "D:\\CVITS\\Program\\Training";
            //string dir = "D:\\CVITS\\Program\\Training";
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetCallingAssembly();
            int pos = assembly.Location.LastIndexOf('\\');
            string dir = assembly.Location.Substring(0, pos);
            string solutionbase = dir.Substring(0, dir.LastIndexOf('\\'));
            string trainingset=solutionbase+"\\GaborRec\\Training";
            if(!System.IO.Directory.Exists(trainingset))
            {
                string trainingset2 = dir + "\\training";
                if(!System.IO.Directory.Exists(trainingset2))
                {
                    throw new Exception("找不到目录‘"+trainingset+"’或目录‘"+trainingset2+"’！");
                }
                trainingset = trainingset2;
            }

            Train(trainingset);
        }

        public void Train(string sampledirbase)
        {
            string[] subdirs = System.IO.Directory.GetDirectories(sampledirbase);
            this.Train(subdirs);
        }

        public void Train(string[] sampledirs)
        {
            int trainSampleCount = 150;
            List<EmguSample> samples = new List<EmguSample>();
            List<Node[]> _X = new List<Node[]>();
            List<double> _Y = new List<double>();
            for (int i = 0; i < sampledirs.Length; i++)
            {
                char symbol = sampledirs[i][sampledirs[i].Length - 1];
                Symbols.Add(symbol);
                string[] images = System.IO.Directory.GetFiles(sampledirs[i], "*.bmp");


                for (int j = 0; j < images.Length; j++)
                {
                    try
                    {
                        Bitmap bitmap = new Bitmap(images[j]);
                        GaborEmgu test = new GaborEmgu();
                        EmguSample sample = new EmguSample(bitmap);
                        sample.Gabor = test.GaborTransform(sample.Image);
                        _X.Add(sample.ToNodes());
                        _Y.Add(i + 1);
                        //_X.Add(sample.ToNodes());
                        //
                        samples.Add(sample);
                    }
                    catch (System.Exception e)
                    {
                        throw new Exception();
                    }
                }
                //_Y.Add(i + 1);
            }
            Matrix<float> trainData = new Matrix<float>(trainSampleCount, 2);
            Matrix<float> trainClasses = new Matrix<float>(trainSampleCount, 1);

            Problem problem = new Problem(_X.Count, _Y.ToArray(), _X.ToArray(), 1024);
            RangeTransform range = RangeTransform.Compute(problem);
            this.range = RangeTransform.Compute(problem);
            problem = range.Scale(problem);

            Parameter param = new Parameter();
            param.C = 2;
            param.Gamma = .5;
            this.model = Training.Train(problem, param);
        }  //SVM形成模型
        #endregion
        char CategoryToSymbol(int category)
        {
            return this.Symbols[category - 1];
        }
        #region SVMtest
        public char SVMtest(Bitmap bmp)
        {
           
                    GaborEmgu test = new GaborEmgu();
                   // System.IO.MemoryStream  imgstream = new System.IO.MemoryStream();
                   // System.Drawing.Image bitmap = new System.Drawing.Image();
                   //bitmap.Save(imgstream, System.Drawing .Imaging .ImageFormat.Jpeg );
                   // byte[] bytes = { };
                   // bytes = imgstream.ToArray();
                    EmguSample sample = new EmguSample(bmp);
                    sample.Gabor = test.GaborTransform(sample.Image);
                   
                 //range = RangeTransform.Compute(problem);
                    //this.range = RangeTransform.Compute(problem);
                Node[] input = sample.ToNodes();
                Node[] features = range.Transform(input);

                //SvmNetTest m = new SvmNetTest();
             
                double result = SVM.Prediction.Predict(model, features); //SVM分类结果
                return this.CategoryToSymbol((int)result);
            }
        
       
        #endregion
    }
}

